package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 实现过滤器需要实现Filter接口
 */
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // 该类的作用主要用于匹配url地址
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //本次强制类型转换是为了使用子类的特有方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1. 获取本次请求uri   http://localhost:8080/backend/index.html
        String requestURI = request.getRequestURI();

        //2 定义一批可以直接放行的资源地址
        String[] urls = {
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //3. 判断本次请求的uri是否需要放行
        boolean flag = checkUri(urls, requestURI);
        if (flag) {
            //本次请求的路径是属于不需要拦截的地址，可以直接放行
            filterChain.doFilter(request, response);
            return;
        }

        //4. 检查是否登陆了,如果已经登陆可以直接放行
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            //用户已经登陆
            filterChain.doFilter(request, response);
            return;
        }


        //前台页面的登陆校验
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            //用户已经登陆
            filterChain.doFilter(request, response);
            return;
        }


        //由于这里不是controller，所以你返回对象的时候需要自己的转换为json，并且写出
        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);
        //5. 如果没有登陆返回错误信息，回到登陆页面

    }

    //检查本次的请求是否符合放行的
    private boolean checkUri(String[] urls, String requestURI) {
        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
